import { memo, useCallback, useEffect, useState } from 'react';
import { useNavigate, useParams, useSearchParams } from 'react-router-dom';
import NotFound from '@/pages/404';
import { Breadcrumb, Pagination } from 'antd';
import { HomeOutlined } from '@ant-design/icons';
import {
  CourseCategory,
  CourseList,
  getCourseCategoryApi,
  getCourseListByQueryApi,
} from '@/api/api';
import ClassroomItem from '@/components/ClassroomItem/ClassroomItem';

// 节日、节气、生肖、星座分类页面
const Classify = () => {
  const { type } = useParams();
  const [query, setQuery] = useSearchParams();
  const classify = query.get('classify');
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [total, setTotal] = useState(0);

  const navigate = useNavigate();
  // 分类配置
  const [categoryConfig, setCategoryConfig] = useState<CourseCategory[]>([]);
  // 课程列表
  const [courseList, setCourseList] = useState<CourseList[]>([]);

  // 获取分类数据
  const getCategoryConfig = useCallback(async () => {
    if (['festival', 'solarTerm', 'zodiac', 'chineseZodiac'].includes(type as string)) {
      const res = await getCourseCategoryApi(
        type as 'festival' | 'solarTerm' | 'zodiac' | 'chineseZodiac'
      );
      setCategoryConfig(
        res.data.map((item) => {
          return {
            ...item,
            children: [
              {
                id: 'all',
                label: '全部',
                parent_id: '',
              },
              ...item.children,
            ],
          };
        })
      );
      return res.data;
    }
  }, [type]);

  // 根据分类和查询参数获取课程列表
  const getCourseList = useCallback(async () => {
    const res = await getCourseListByQueryApi({
      type: type as 'festival' | 'solarTerm' | 'zodiac' | 'chineseZodiac',
      classify: classify as string,
      page,
      pageSize,
    });
    setCourseList(res.data.data);
    setTotal(res.data.total);
  }, [type, classify, page, pageSize]);

  useEffect(() => {
    // 获取分类配置
    getCategoryConfig();
  }, [getCategoryConfig]);

  useEffect(() => {
    // 获取课程列表
    getCourseList();
  }, [getCourseList, type]);

  // 点击分类项处理函数
  const handleCategoryClick = (categoryId: string) => {
    // 如果点击的是全部，则清除classify参数
    if (categoryId.startsWith('all')) {
      setQuery({});
    } else {
      // 设置新的查询参数并保持当前页面
      setQuery({ classify: categoryId });
    }
  };

  // 如果类型不存在，显示404页面
  if (!type) {
    return <NotFound />;
  }

  return (
    <div className="w-full min-w-[400px] h-full px-[5%] lg:px-[15%] md:px-[10%] sm:px-[5%] pt-[32px]">
      {/* 路径显示 */}
      <Breadcrumb
        items={[
          {
            title: (
              <div
                className="flex-center gap-2 cursor-pointer hover:bg-blue-100 rounded-md px-1 py-1"
                onClick={() => {
                  navigate('/');
                }}
              >
                <HomeOutlined />
                <span>首页</span>
              </div>
            ),
          },
          {
            title: (
              <div className="py-1">
                <span>分类</span>
              </div>
            ),
          },
          {
            title: (
              <div className="py-1">
                <span>{type === 'festival' && '节日'}</span>
                <span>{type === 'solarTerm' && '节气'}</span>
                <span>{type === 'zodiac' && '生肖'}</span>
                <span>{type === 'chineseZodiac' && '星座'}</span>
              </div>
            ),
          },
        ]}
      />
      <div className="max-w-[1200px] mx-auto">
        <div className="w-full border-b border-[#f5f5f5] py-2">
          <div className="w-full">
            {/* 多行分类 */}
            {/* 渲染分类配置 */}
            {categoryConfig.map((category, index) => (
              <div
                key={index}
                className={`flex text-[14px] py-[7px] ${
                  index !== categoryConfig.length - 1 ? 'border-b border-[#f5f5f5]' : ''
                }`}
              >
                {/* 分类标签 */}
                <div className="mr-[15px] text-right flex-shrink-0 flex pt-1">{category.label}</div>
                <div className="flex flex-wrap gap-[15px]">
                  {/* 渲染分类选项 */}
                  {category.children.map((option) => (
                    <div
                      key={option.id}
                      className={`cursor-pointer transition-colors border-1 border-[rgba(0,0,0,0)] px-4 py-1  rounded-2xl ${
                        (option.id.startsWith('all') && !classify) || classify === option.id
                          ? 'text-[#333] font-medium bg-[#f5f5f5]'
                          : 'text-[#666]  hover:text-[#333]  hover:border-[#6f6f6f]'
                      }`}
                      onClick={() => handleCategoryClick(option.id)}
                    >
                      <span>{option.label}</span>
                    </div>
                  ))}
                </div>
              </div>
            ))}
          </div>
        </div>
        {/* 课程列表 */}
        <div className="max-w-[1200px] mx-auto">
          {/* 课程列表标题 */}
          <div className="mb-6">
            <h2 className="text-xl font-medium text-[#333]">
              {type === 'festival' && '节日课程'}
              {type === 'solarTerm' && '节气课程'}
              {type === 'zodiac' && '生肖课程'}
              {type === 'chineseZodiac' && '星座课程'}
              {classify &&
                ` - ${
                  categoryConfig.flatMap((cat) => cat.children).find((item) => item.id === classify)
                    ?.label
                }`}
            </h2>
          </div>

          {/* 课程列表 */}
          <div className="grid grid-cols-[repeat(auto-fill,minmax(326px,1fr))] gap-4">
            {/* 这里将根据分类展示相应的课程列表 */}
            {courseList.map((item) => (
              <ClassroomItem
                key={item.id}
                classroomData={item}
              />
            ))}
          </div>

          {/* 分页 */}
          <div className="flex justify-center items-center py-8">
            <Pagination
              total={total}
              pageSize={pageSize}
              current={page}
              onChange={(page, pageSize) => {
                setPage(page);
                setPageSize(pageSize);
              }}
            />
            <div className="text-[#666] !text-[16px]">共{total}条</div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default memo(Classify);
